package com.zoke.daycarpool.domain;

import com.zoke.support.base.BaseApp;
import com.zoke.support.db.JackDb;
import com.zoke.support.utils.PersistTool;

import android.content.Context;
import android.text.TextUtils;

/**
 * @author JackWu
 */
public class UserInstense {
	private Context mContext;

	private JackDb mDb;

	private UserBeen mUserBeen;

	private static final String USERID = "_userid";

	private UserInstense(Context context) {
		this.mContext = context;
		mDb = ((BaseApp) mContext.getApplicationContext()).createDb();
	}

	/** 初始化用户信息 **/
	public UserBeen initUser() {
		String userId = PersistTool.getString(USERID, "");
		if (TextUtils.isEmpty(userId))
			return mUserBeen;
		if (mDb == null)
			return mUserBeen;
		mUserBeen = mDb.findById(userId, UserBeen.class);
		return mUserBeen;
	}

	/** 判断是否登陆 **/
	public boolean isLogin() {
		String userId = PersistTool.getString(USERID, "");
		return !TextUtils.isEmpty(userId);
	}

	/** 存储UserBeen **/
	public void saveUser(UserBeen userBeen) {
		if (mDb == null)
			return;
		if (userBeen == null)
			return;
		UserBeen usered = mDb.findById(userBeen.getUserId(), UserBeen.class);
		if (usered == null)
			mDb.save(userBeen);
		mUserBeen = userBeen;
		PersistTool.saveString(USERID, mUserBeen.getUserId());
	}

	/** 退出登陆 清空登陆信息 **/
	public void loginOut(UserBeen userBeen) {
		if (mDb == null)
			return;
		if (userBeen == null)
			return;
		mDb.delete(userBeen);
		PersistTool.saveString(USERID, "");
	}

	/** 更新UserBeen **/
	public void updateUser(UserBeen userBeen) {
		if (mDb == null)
			return;
		if (userBeen == null)
			return;
		mDb.update(userBeen);
		mUserBeen = userBeen;
	}

	/** 获取登陆用户的信息 **/
	public UserBeen getUser() {
		return mUserBeen;
	}

	private static UserInstense mUser;

	/** 初始化 **/
	public static synchronized UserInstense getInstense(Context context) {
		if (mUser == null)
			mUser = new UserInstense(context);
		return mUser;
	}

}
